package com.sz.app.edi.rest.edi.track;

import com.sz.app.edi.base.entity.SynCompanyAccount;
import com.sz.app.edi.base.service.SynCompanyAccountService;
import com.sz.app.edi.constants.EdiErrorCodes;
import com.sz.app.edi.rest.edi.base.LogisticsRequest;
import com.sz.app.edi.rest.edi.base.Responses;
import com.sz.app.edi.rest.edi.track.dto.Orders;
import com.sz.app.edi.rest.edi.track.dto.ReceNormalOrders;
import com.sz.app.edi.service.order.CusOrderTrackingService;
import com.sz.biz.app.web.BaseController;
import com.sz.biz.common.constants.MessagesCodes;
import com.sz.biz.logistics.constants.OrderConstants;
import com.sz.biz.logistics.ord.dto.OrdOrderTrackingShowDto;
import com.sz.biz.logistics.ord.entity.ConvertStatus;
import com.sz.biz.logistics.ord.service.OrdOrderService;
import com.sz.common.base.dto.ResultDto;
import com.sz.common.base.exception.Exceptions;
import com.sz.common.base.utils.JsonUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Function: 数据交换平台客户同步物流controller
 * Author: hpeng.wang.<br>
 * Date: 2017-06-23 16:08:00.
 */
@RestController
@RequestMapping("${out}/order/tracks")
@Api(description = " ", tags = "051-002、EDI-订单-客户同步物流信息")
public class CusOrderTrackingController extends BaseController {
    @Autowired
    private CusOrderTrackingService cusOrderTrackingService;
    @Autowired
    private SynCompanyAccountService synCompanyAccountService;
    @Autowired
    private OrdOrderService orderService;

    /**
     * 根据waybillNo查询物流信息
     *
     * @param waybillNo 订单的waybillNo
     * @return 查询到的物流信息
     */
    @RequestMapping(value = "/{waybillNo}", method = RequestMethod.GET)
    @ApiOperation(value = "查询物流_waybillNo", notes = "根据waybillNo获取订单的物流信息")
    public ResultDto findTrackByWaybillNo(@ApiParam(value = "订单waybillNo", required = true) @PathVariable String waybillNo) {
        List<Integer> rankList = new ArrayList<>();
        rankList.add(OrderConstants.OrderTrackRank.TRACKING_CUSTOMER);
        Map<String, List<OrdOrderTrackingShowDto>> orderTrackingMap = orderService.findTrackByWaybillNo(rankList, waybillNo);
        ResultDto result = new ResultDto();
        result.setData(orderTrackingMap);
        return result;
    }


    /**
     * 第一个供应商收到货后，返回订单详细信息.
     */
    @ApiOperation(value = "新增", notes = "供应商收到货后，返回订单的数据信息")
    @RequestMapping(value = "/orderdata", method = {RequestMethod.POST})
    public ResultDto orderData(@RequestBody @ApiParam(value = "要添加的物流信息", required = true) @Validated LogisticsRequest dto) {

        //1、保存原始的物流消息
        int originalId = cusOrderTrackingService.processOriginalAndSave(dto);

        //2、根据token获取供应商或客户对应的信息
        SynCompanyAccount synCompanyAccount = synCompanyAccountService.findByToken(dto.getEventHead().getToken());
        if (ObjectUtils.isEmpty(synCompanyAccount)) {
            throw Exceptions.bizException(EdiErrorCodes.ERROR_EDI_ORD_TRACKING_SYN_COMPANY_NOT_FOUND);
        }

        ConvertStatus convertStatus;
        LinkedHashMap orderMap = (LinkedHashMap) dto.getEventBody().getData();
        Object orders = JsonUtils.toObject(JsonUtils.toJSONString(orderMap.get("orders")), Orders.class);
        if (orders instanceof Orders) {
            convertStatus = cusOrderTrackingService.processReceGoodTacking((Orders) orders, synCompanyAccount.getBizId(), originalId);
        } else {
            throw Exceptions.bizException(EdiErrorCodes.ERROR_ARGUMENT);
        }
        cusOrderTrackingService.updateConvertStatus(originalId, convertStatus);
        ResultDto result = getSaveSuccessDto(MessagesCodes.MODULE_ORDER_TRACKING);
        return result;
    }

    /**
     * 收到供应商发过来的正常物流信息.
     */
    @ApiOperation(value = "新增", notes = "供应商正常的物流消息")
    @RequestMapping(value = "/nomaltracking", method = {RequestMethod.POST})
    public Responses normalTracking(@RequestBody @ApiParam(value = "正常物流消息dto", required = true) @Validated LogisticsRequest dto) {
        //1、保存原始的物流消息
        int originalId = cusOrderTrackingService.processOriginalAndSave(dto);

        //2、根据token获取供应商或客户对应的信息
        SynCompanyAccount synCompanyAccount = synCompanyAccountService.findByToken(dto.getEventHead().getToken());
        if (ObjectUtils.isEmpty(synCompanyAccount)) {
            throw Exceptions.bizException(EdiErrorCodes.ERROR_EDI_ORD_TRACKING_SYN_COMPANY_NOT_FOUND);
        }

        LinkedHashMap orderMap = (LinkedHashMap) dto.getEventBody().getData();
        String batchNo = (String) orderMap.get("batchNo");
        ReceNormalOrders orders = JsonUtils.toObject(JsonUtils.toJSONString(orderMap.get("orders")), ReceNormalOrders.class);
        cusOrderTrackingService.processNormalTracking(batchNo, orders, synCompanyAccount.getBizId(), originalId);

        return Responses.responses();

    }


    /**
     * 收到供应商发过来的异常物流信息.
     */
    @ApiOperation(value = "新增", notes = "供应商发过来的异常的物流消息")
    @RequestMapping(value = "/abnomaltracking", method = {RequestMethod.POST})
    public Responses abnormalTracking(@RequestBody @ApiParam(value = "异常物流消息dto", required = true) @Validated LogisticsRequest dto) {
        //1、保存原始的物流消息
        int originalId = cusOrderTrackingService.processOriginalAndSave(dto);

        //2、根据token获取供应商或客户对应的信息
        SynCompanyAccount synCompanyAccount = synCompanyAccountService.findByToken(dto.getEventHead().getToken());
        if (ObjectUtils.isEmpty(synCompanyAccount)) {
            throw Exceptions.bizException(EdiErrorCodes.ERROR_EDI_ORD_TRACKING_SYN_COMPANY_NOT_FOUND);
        }

        LinkedHashMap orderMap = (LinkedHashMap) dto.getEventBody().getData();
        ReceNormalOrders orders = JsonUtils.toObject(JsonUtils.toJSONString(orderMap.get("orders")), ReceNormalOrders.class);
        return Responses.responses();

    }
}